package jp.tkym.labs.store;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

class SqliteBeanstoreServiceFactory implements BeanstoreServiceFactory{
	private static final String JDBC_PATH = "org.sqlite.JDBC";
	private boolean autoCommit = false;
	
	SqliteBeanstoreServiceFactory() throws BeanstoreException{
		try {
			Class.forName(JDBC_PATH);
		} catch (ClassNotFoundException e) {
			throw new BeanstoreException(e);
		}
	}
	
	@Override
	public BeanstoreService createBeanstoreService(String filePath) throws BeanstoreException{
		try {
			Connection connection = createConnection(filePath);
			initialize(connection);
			return new SqliteBeanstoreService(connection);
		} catch (SQLException e) {
			throw new BeanstoreException(e);
		}
	}
	
	private void initialize(Connection connection) throws SQLException{
		connection.setAutoCommit(autoCommit);
	}
	
	private Connection createConnection(String filePath) throws SQLException{
		return DriverManager.getConnection("jdbc:sqlite:"+filePath);
	}
}